package com.meb.imageexif

import android.annotation.SuppressLint
import androidx.exifinterface.media.ExifInterface
import com.amap.api.maps2d.model.LatLng
import com.blankj.utilcode.util.LogUtils
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.tools.SdkVersionUtils
import java.io.IOException
import java.math.BigDecimal
import java.text.SimpleDateFormat
import kotlin.math.abs
import kotlin.math.floor

fun LocalMedia.toPath(): String {
    return when {
        this.isCut -> cutPath
        this.isCompressed -> compressPath
        this.isOriginal -> originalPath
        else -> {
            if (SdkVersionUtils.checkedAndroid_Q()) {
                androidQToPath
            } else {
                path
            }
        }
    }
}

/**
 * 获取转换后的经纬度
 */
fun getNormalLATandLong(imagePath: String): LatLng {
    var latitude: Double = 0.0
    var longitude: Double = 0.0
    try {
        val exifInterface = ExifInterface(imagePath)
        var latitudeStr = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE)
        var longitudeStr = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)
        if (latitudeStr.isNullOrEmpty() && longitudeStr.isNullOrEmpty() && longitudeStr != "0.0" && latitudeStr != "0.0") {
            latitudeStr = latitudeStr?.replace("/", ",")
            longitudeStr = longitudeStr?.replace("/", ",")
            val lat = latitudeStr?.split(",")
            val lng = longitudeStr?.split(",")
            var latD = 0f
            var latM = 0f
            var latS = 0f
            var lngD = 0f
            var lngM = 0f
            var lngS = 0f
            if (lat != null && lng != null) {
                if (lat.size >= 2) {
                    latD = lat[0].toFloat() / lat[1].toFloat()
                }
                if (lat.size >= 4) {
                    latM = lat[2].toFloat() / lat[3].toFloat()
                }
                if (lat.size >= 6) {
                    latS = lat[4].toFloat() / lat[5].toFloat()
                }
                if (lng.size >= 1) {
                    lngD = lng[0].toFloat() / lng[1].toFloat()
                }
                if (lng.size >= 2) {
                    lngM = lng[2].toFloat() / lng[3].toFloat()
                }
                if (lng.size >= 3) {
                    lngS = lng[4].toFloat() / lng[5].toFloat()
                }
            }

            latitude = (latD + latM / 60 + latS / 3600).toDouble()
            longitude = (lngD + lngM / 60 + lngS / 3600).toDouble()
        }
    } catch (e: IllegalArgumentException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    }



    return LatLng(latitude, longitude)
}

/**
 * 将小数度数转换为度分秒格式
 *
 * @param numStr （主要用于图片中存储经纬度）
 * @return
 */
fun convertToSexagesimal(numStr: String): String? {
    val num = numStr.toDouble()
    val du = floor(abs(num)).toInt() //获取整数部分
    val temp: Double = getdPoint(abs(num)) * 60
    val fen = floor(temp).toInt() //获取整数部分
    val miao: Double = getdPoint(temp) * 60
    return if (num < 0) "-$du/1,$fen/1,$miao/1" else "$du/1,$fen/1,$miao/1"
}

//获取小数部分
private fun getdPoint(num: Double): Double {
    val fInt = num.toInt()
    val b1 = BigDecimal(num.toString())
    val b2 = BigDecimal(fInt.toString())
    return b1.subtract(b2).toFloat().toDouble()
}

fun logImageInfo(imgUrl: String): ExifInterface? {
    try {
        var exifInterface = ExifInterface(imgUrl)
        LogUtils.d(
            "手机品牌: " + exifInterface!!.getAttribute(ExifInterface.TAG_MAKE)
        )
        LogUtils.d(
            "手机型号: " + exifInterface!!.getAttribute(ExifInterface.TAG_MODEL)
        )

        LogUtils.d(
            "拍摄时间: " + exifInterface!!.getAttribute(ExifInterface.TAG_DATETIME)
        )
        LogUtils.d(
            "数字化时间: " + exifInterface!!.getAttribute(ExifInterface.TAG_DATETIME_DIGITIZED)
        )
        LogUtils.d(
            "曝光时间: " + exifInterface!!.getAttribute(ExifInterface.TAG_EXPOSURE_TIME)
        )
        LogUtils.d(
            "闪光灯: " + exifInterface!!.getAttribute(ExifInterface.TAG_FLASH)
        )
        LogUtils.d(
            "焦距: " + exifInterface!!.getAttribute(ExifInterface.TAG_FOCAL_LENGTH)
        )
        LogUtils.d(
            "海拔高度: " + exifInterface!!.getAttribute(ExifInterface.TAG_GPS_ALTITUDE)
        )
        LogUtils.d(
            "海拔高度: " + exifInterface!!.getAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF)
        )
        LogUtils.d(
            "GPS纬度名: " + exifInterface!!.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF)
        )
        LogUtils.d(
            "GPS纬度: " + exifInterface!!.getAttribute(ExifInterface.TAG_GPS_LATITUDE)
        )
        LogUtils.d(
            "GPS经度名: " + exifInterface!!.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF)
        )
        LogUtils.d(
            "GPS经度: " + exifInterface!!.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)
        )
        LogUtils.d(
            "GPS日期戳: " + exifInterface!!.getAttribute(ExifInterface.TAG_GPS_DATESTAMP)
        )
        LogUtils.d(
            "GPS时间戳: " + exifInterface!!.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP)
        )
        LogUtils.d(
            "图片高度: " + exifInterface!!.getAttribute(ExifInterface.TAG_IMAGE_LENGTH)
        )
        LogUtils.d(
            "图片宽度: " + exifInterface!!.getAttribute(ExifInterface.TAG_IMAGE_WIDTH)
        )

        LogUtils.d(
            "旋转角度: " + exifInterface!!.getAttribute(ExifInterface.TAG_ORIENTATION)
        )
        LogUtils.d(
            "白平衡: " + exifInterface!!.getAttribute(ExifInterface.TAG_WHITE_BALANCE)
        )
        LogUtils.d(
            "TAG_SUBSEC_TIME: " + exifInterface!!.getAttribute(ExifInterface.TAG_SUBSEC_TIME)
        )


//        val normalGps = getNormalLATandLong(
//            exifInterface!!.getAttribute(ExifInterface.TAG_GPS_LATITUDE),
//            exifInterface!!.getAttribute(
//                ExifInterface.TAG_GPS_LONGITUDE
//            )
//        )
//            iv_info.text = "选择图片的经纬度：" + normalGps[0].toString() + "/" + normalGps[1].toString()
            return exifInterface
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return null
}

/**
 * GMT(格林威治标准时间)转换当前北京时间
 * 比如：1526217409 -->2018/5/13 21:16:49 与北京时间相差8个小时，调用下面的方法，是在1526217409加上8*3600秒
 * @param GMT 秒单部位
 * @return
 */
@SuppressLint("SimpleDateFormat")
fun dateGmtTOCst(GMT: Long): String? {
    val lt = GMT+ 8 * 3600
    var res: String? = null
    try {
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        res = simpleDateFormat.format(lt)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return res
}

@SuppressLint("SimpleDateFormat")
fun dateCstTOGmt(CST: Long): String? {
    val lt = CST - 8 * 3600
    var res: String? = null
    try {
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        res = simpleDateFormat.format(lt)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return res
}